package yunjiao.javatutorials.designpatterns.combinator;

import java.util.function.Function;

/**
 * 解析器
 *
 * @author yangyunjiao
 */
public class BasicParsers {
    // 解析特定字符串
    public static Parser<String> string(String target) {
        return input -> {
            if (input.startsWith(target)) {
                return ParseResult.success(target, input.substring(target.length()));
            }
            return ParseResult.failure("Expected: " + target);
        };
    }

    // 解析单个字符
    public static Parser<Character> character(char c) {
        return input -> {
            if (!input.isEmpty() && input.charAt(0) == c) {
                return ParseResult.success(c, input.substring(1));
            }
            return ParseResult.failure("Expected character: " + c);
        };
    }

    // 解析任意字符
    public static Parser<Character> anyChar() {
        return input -> {
            if (!input.isEmpty()) {
                return ParseResult.success(input.charAt(0), input.substring(1));
            }
            return ParseResult.failure("Unexpected end of input");
        };
    }

    // 解析满足条件的字符
    public static Parser<Character> satisfy(Function<Character, Boolean> predicate) {
        return input -> {
            if (!input.isEmpty()) {
                char c = input.charAt(0);
                if (predicate.apply(c)) {
                    return ParseResult.success(c, input.substring(1));
                }
            }
            return ParseResult.failure("Character does not satisfy predicate");
        };
    }

    // 解析数字
    public static Parser<Character> digit() {
        return satisfy(Character::isDigit);
    }

    // 解析字母
    public static Parser<Character> letter() {
        return satisfy(Character::isLetter);
    }

    // 解析空白字符
    public static Parser<Character> whitespace() {
        return satisfy(Character::isWhitespace);
    }
}
